package com.smile.service.handler;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smile.mapper.*;
import com.smile.model.domain.FeisuanAirport;
import com.smile.model.domain.FeisuanAirportDrone;
import com.smile.model.domain.FeisuanDrone;
import com.smile.model.domain.SmilePlusOrganization;
import com.smile.service.config.mqtt.handler.AbstractAirportOrganizationBindHandler;
import com.smile.service.entity.organization.AirportBindErrorResult;
import com.smile.service.entity.response.DeviceConfigResponse;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
public class DefaultAirportOrganizationBindHandler extends AbstractAirportOrganizationBindHandler {
    @Autowired
    private OrganizationMapper organizationMapper;


    @Autowired
    private AirportDroneMapper airportDroneMapper;

    @Autowired
    private AirportMapper airportMapper;

    @Autowired
    private DroneMapper droneMapper;

    @Autowired
    private DeviceModelMapper deviceModelMapper;

    @Override
    public Boolean process(String data, String tid, String bid,String gateway) throws MqttException {

        System.out.println(data);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);

        DeviceConfigResponse<AirportBindErrorResult> deviceConfigResponse = new DeviceConfigResponse<>();
        deviceConfigResponse.setBid(bid);
        deviceConfigResponse.setTid(tid);
//        {"bind_devices":[{"device_binding_code":"iQfc2X","device_nonce":"096ebfe2093c53650721ea36146bc2fb","organization_id":"9veeb2","sn":"7CTXN6R00B0C5L","device_secret":"3daa4b13340b715c2639a4110e32194a","device_callsign":"","device_model_key":"3-2-0"}]}
        List<Map<String, Object>> list = (List<Map<String, Object>>)jsonObject.get("bind_devices");
        List<AirportBindErrorResult.ErrorInfo> errorInfoList = new ArrayList<>();
        Boolean result = false;
        for (Map<String, Object> map : list) {
            System.out.println(map);
            System.out.println(map.get("device_binding_code"));
            System.out.println(map.get("device_nonce"));
            System.out.println(map.get("organization_id"));
            System.out.println(map.get("sn"));
            System.out.println(map.get("device_secret"));
            System.out.println(map.get("device_model_key"));
            if(!map.get("device_model_key").equals("")){
                String[] arr = map.get("device_model_key").toString().split("-");
                String domain = arr[0];
                String type = arr[0];
                String sub_type = arr[0];
                if (domain.equals("3")){//机场
                    //机场 查询当前机场是否存在
                    QueryWrapper<FeisuanAirport> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("gateway_sn", map.get("sn"));
                    FeisuanAirport feisuanAirport = airportMapper.selectOne(queryWrapper);
                    if (feisuanAirport == null || Objects.isNull(feisuanAirport)){
                       feisuanAirport = new FeisuanAirport();
                       //查询组织id和设备绑定码
                        QueryWrapper<SmilePlusOrganization> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.eq("device_binding_code", map.get("device_binding_code"));
                        queryWrapper1.eq("organization_code", map.get("organization_id"));
                        SmilePlusOrganization organization = organizationMapper.selectOne(queryWrapper1);
                        if (organization != null){

                            feisuanAirport.setAirportName(map.get("device_callsign").toString());
                            feisuanAirport.setOrganizationId(organization.getId());
                            feisuanAirport.setCreateTime(LocalDateTime.now());
                            feisuanAirport.setModifyTime(LocalDateTime.now());
                            feisuanAirport.setGateway(map.get("sn").toString());
                            feisuanAirport.setGatewaySn(map.get("sn").toString());
                            feisuanAirport.setStatus(1);
                            feisuanAirport.setDeviceModelKey(map.get("device_model_key").toString());
                            airportMapper.insert(feisuanAirport);
                            AirportBindErrorResult.ErrorInfo errorInfo = new AirportBindErrorResult.ErrorInfo();
                            errorInfo.setErrorCode(0);
                            errorInfo.setSerialNumber(map.get("sn").toString());
                            errorInfoList.add(errorInfo);

                        }else{
                            AirportBindErrorResult.ErrorInfo errorInfo = new AirportBindErrorResult.ErrorInfo();
                            errorInfo.setErrorCode(9502);
                            errorInfo.setSerialNumber(map.get("sn").toString());
                            errorInfoList.add(errorInfo);
                        }
                    }else{//飞行器
                        result = true;
                        //查询是否存在机场
                        AirportBindErrorResult.ErrorInfo errorInfo = new AirportBindErrorResult.ErrorInfo();
                        errorInfo.setErrorCode(0);
                        errorInfo.setSerialNumber(map.get("sn").toString());
                        errorInfoList.add(errorInfo);
                    }
                }else if (domain.equals("0")){
                    //查询是否存在机场
                    String droneSn = map.get("sn").toString();
                    if (!droneSn.equals("")){
                        QueryWrapper<FeisuanDrone> queryWrapper2 = new QueryWrapper<>();
                        queryWrapper2.eq("drone_sn", map.get("sn"));
                        FeisuanDrone feisuanDrone = droneMapper.selectOne(queryWrapper2);
                        if (feisuanDrone == null){
                            QueryWrapper<FeisuanAirport> queryWrapper3 = new QueryWrapper<>();
                            queryWrapper3.eq("gateway_sn", gateway);
                            FeisuanAirport feisuanAirport1 = airportMapper.selectOne(queryWrapper3);
                            FeisuanDrone feisuanDrone1 = new FeisuanDrone();
                            QueryWrapper<SmilePlusOrganization> queryWrapper4 = new QueryWrapper<>();

                            queryWrapper4.eq("device_binding_code", map.get("device_binding_code"));
                            queryWrapper4.eq("organization_code", map.get("organization_id"));
                            SmilePlusOrganization organization = organizationMapper.selectOne(queryWrapper4);
                            if (organization == null){
                                AirportBindErrorResult.ErrorInfo errorInfo = new AirportBindErrorResult.ErrorInfo();
                                errorInfo.setErrorCode(9502);
                                errorInfo.setSerialNumber(map.get("sn").toString());
                                errorInfoList.add(errorInfo);
                            }else{
                                feisuanDrone1.setOrganizationId(organization.getId());
                                feisuanDrone1.setCreateTime(LocalDateTime.now());
                                feisuanDrone1.setModifyTime(LocalDateTime.now());
                                feisuanDrone1.setDroneSn(map.get("sn").toString());
                                feisuanDrone1.setStatus(1);
                                feisuanDrone1.setDeleteStatus(false);
                                feisuanDrone1.setDroneBrand("大疆");
                                feisuanDrone1.setDeviceModelKey(map.get("device_model_key").toString());
                                Integer id = droneMapper.insert(feisuanDrone1);
                                if (feisuanAirport1 != null){
                                    //先删除已绑定的无人机 目前的业务不涉及到跳蛙任务
                                    QueryWrapper<FeisuanAirportDrone> queryWrapper5 = new QueryWrapper<>();
                                    queryWrapper5.eq("airport_id", feisuanAirport1.getId());
                                    airportDroneMapper.delete(queryWrapper5);
                                    //添加新增的设备
                                    FeisuanAirportDrone feisuanAirportDrone = new FeisuanAirportDrone();
                                    feisuanAirportDrone.setAirportId(feisuanAirport1.getId());
                                    feisuanAirportDrone.setDroneId(id.longValue());
                                    airportDroneMapper.insert(feisuanAirportDrone);
                                }
                                result = true;
                                AirportBindErrorResult.ErrorInfo errorInfo = new AirportBindErrorResult.ErrorInfo();
                                errorInfo.setErrorCode(0);
                                errorInfo.setSerialNumber(map.get("sn").toString());
                                errorInfoList.add(errorInfo);
                            }
                    }else{
                            AirportBindErrorResult.ErrorInfo errorInfo = new AirportBindErrorResult.ErrorInfo();
                            errorInfo.setErrorCode(0);
                            errorInfo.setSerialNumber(map.get("sn").toString());
                            errorInfoList.add(errorInfo);
                        }
                        //查询
                    }else{ //查询到有数据不在处理
                        result = true;
                        AirportBindErrorResult.ErrorInfo errorInfo = new AirportBindErrorResult.ErrorInfo();
                        errorInfo.setErrorCode(0);
                        errorInfo.setSerialNumber(map.get("sn").toString());
                        errorInfoList.add(errorInfo);
                    }
                }
            }
        }
        AirportBindErrorResult airportBindErrorResult = new AirportBindErrorResult();
        airportBindErrorResult.setResultCode(0);
        AirportBindErrorResult.BindErrorOutput bindErrorOutput = new AirportBindErrorResult.BindErrorOutput();


        bindErrorOutput.setErrorInfos(errorInfoList);
        airportBindErrorResult.setOutput(bindErrorOutput);
        deviceConfigResponse.setData(airportBindErrorResult);
        deviceConfigResponse.setTimestamp(System.currentTimeMillis());
        deviceConfigResponse.setMethod("airport_organization_bind");


        if (jsonObject.containsKey("gateway")) {
            deviceConfigResponse.setGateway(jsonObject.getString("gateway"));
        }else{
            deviceConfigResponse.setGateway(gateway);
        }

        log.info("DefaultAirportOrganizationBindHandler {}", JSONObject.toJSONString(deviceConfigResponse));
        MqttMessage message = new MqttMessage();
        message.setQos(0);
        message.setRetained(true);
        message.setPayload(JSONObject.toJSONString(deviceConfigResponse).getBytes());
        MqttClient mqttClient = new MqttClient("tcp://120.211.119.131:1883", "feisuan-mqtt-producer-client", new MemoryPersistence());
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName("feisuan");
        connOpts.setPassword("feisuan123456".toCharArray());
        mqttClient.connect(connOpts);
        JSONObject.toJSONString(deviceConfigResponse);
        System.out.println(message);
        mqttClient.publish("thing/product/" + gateway + "/requests_reply", message);
        return Boolean.TRUE;
    }
}
